package com.Rest2Go;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.util.GeoPoint;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.Rest2Go.Utils.SimplePhotoCache;
import com.Rest2Go.Utils.Utils;

public class NewRestActivity extends ActivityWrapper
{

	private MoveEatGallery							mTabGallery;
	// private ViewStub viewStub;
	private long									mRestId;
	private SimplePhotoCache						photos;
	private int										mCount;
	private ArrayList<String>						galleryMenuArray;
	private NewMenuDataAdapter						galleryMenuAdapter;
	private MoveEatViewGalleryAdapter				mViewGalleryAdapter;
	private ArrayList<MenuHandler>					menuHandlers;
	private HashMap<Integer, Pair<Long, String>>	mMenuIds;
	private View									mRestView;
	private MoveEatGallery							mViewGallery;
	private RestMap									mMapView;
	private HashMap<Integer, String>				mCatHashMap;
	private int										mMoveEatUID;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Log.d("RONI", "NewRestActivity");
		setContentView(R.layout.new_rest_layout);
		//mTabGallery = (MoveEatGallery) findViewById(R.id.gallery);
		mTabGallery.setScrollbarFadingEnabled(true);
		mTabGallery.setScrollBarStyle(Gallery.SCROLLBARS_INSIDE_OVERLAY);
		Intent intent = getIntent();
		mRestId = intent.getLongExtra(Consts.Extras.REST_ID, -1);
		//mCatHashMap = ((HashMap<Integer, String>) intent.getSerializableExtra(Consts.Extras.CATS));
		mMoveEatUID = intent.getIntExtra(Consts.Extras.ME_UID, -1);
		mViewGallery = (MoveEatGallery) findViewById(R.id.main_view_gallery);

		mTabGallery.setControlledGallery(mViewGallery);
		mViewGallery.setControlledGallery(mTabGallery);

		if (mRestId >= 0)
		{
			Utils.log("getting Rest Details");
			getRestDetails();
		}
		else
		{
			finish();
		}

		galleryMenuArray = new ArrayList<String>();
		galleryMenuArray.add("Map");
		galleryMenuArray.add("Info");

		galleryMenuAdapter = new NewMenuDataAdapter(galleryMenuArray, this, mViewGallery, mTabGallery);
		mTabGallery.setAdapter(galleryMenuAdapter);
		mTabGallery.setSelection(1);
	}

	private void getMenuDetails()
	{
		menuHandlers = new ArrayList<MenuHandler>();
		for (int i = 0; i < mCount; i++)
		{
			menuHandlers.add(new MenuHandler(mRestId, this, "", mMenuIds.get(i).second, mMenuIds.get(i).first, mCatHashMap, mMoveEatUID));
		}

	} 

	private void getRestDetails()
	{
		new AsyncTask<Void, String, String>()
		{

			@Override
			protected void onPreExecute()
			{
				NewRestActivity.this.showLoading(this);
			}

			@Override
			protected String doInBackground(Void... arg0)
			{
				String menuReq = Utils.preformRequest(Utils.BASE_URL + "GetMenus.php?rest_id=" + mRestId + "&count=true");
				// int reqEnd = menuReq.indexOf("<");
				// menuReq = menuReq.substring(0, reqEnd);
				Utils.log(menuReq);
				setMenuIds(menuReq);
				return (Utils.preformRequest(Utils.BASE_URL + "GetRestDetails.php?id=" + mRestId + "&menu_count=true"));
			}

			@Override
			protected void onPostExecute(String body)
			{
				Utils.log(body);
				if (body != null)
				{
					JSONObject obj = null;
					try
					{
						obj = new JSONObject(body);
					}
					catch (JSONException e)
					{
						Utils.log("Error creating JSON: " + e.getMessage());
					}
					if (obj != null)
					{
						JSONArray arr = obj.optJSONArray("restaurants");
						JSONArray propArr = obj.optJSONArray("properties");
						setMenuNames();
						mRestView = displayRestDetails(arr, propArr);
						getMenuDetails();
						mViewGalleryAdapter = new MoveEatViewGalleryAdapter(NewRestActivity.this.getBaseContext(), mCount, mTabGallery, mViewGallery,
								menuHandlers, mRestView, mMapView);
						mViewGallery.setAdapter(mViewGalleryAdapter);
						mViewGallery.setSelection(1);
						mViewGallery.invalidate();
					}
					else
					{

					}

					removeDialog(ProgressDialog.STYLE_HORIZONTAL);
				}
			}

		}.execute();

	}

	protected void setMenuIds(String menuIds)
	{
		try
		{
			JSONObject obj = new JSONObject(menuIds);
			JSONArray arr = obj.optJSONArray("menus");
			mMenuIds = new HashMap<Integer, Pair<Long, String>>();
			for (int i = 0; i < arr.length(); i++)
			{
				JSONObject currObj = arr.optJSONObject(i);
				mMenuIds.put(i, new Pair<Long, String>(Long.parseLong(currObj.optString("MENU_ID")), currObj.optString("MENU_NAME")));
			}
			mCount = arr.length();
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}

	}

	protected void setMenuNames()
	{

		for (int i = 0; i < mCount; i++)
		{
			galleryMenuAdapter.add(mMenuIds.get(i).second);
		}
		galleryMenuAdapter.notifyDataSetChanged();
		// galleryMenuAdapter.notifyDataSetInvalidated();
	}

	private View displayRestDetails(JSONArray arr, JSONArray propArr)
	{
		// viewStub.inflate();
		LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.restaurant_layout, null);
		photos = new SimplePhotoCache(getBaseContext().getResources().getDrawable(R.drawable.icon));
		for (int i = 0; i <= arr.length() - 1; i++)
		{
			JSONObject rest = arr.optJSONObject(i);
			String phone2 = "";
			String imageUrl = null;

			TextView restName = (TextView) view.findViewById(R.id.txtRestName);
			TextView restAddress = (TextView) view.findViewById(R.id.txtRestAddress);
			TextView restPhone = (TextView) view.findViewById(R.id.txtRestPhone);
			TextView restPhone2 = (TextView) view.findViewById(R.id.txtRestPhone2);
			ImageView restImage = (ImageView) view.findViewById(R.id.restImg);

			// long mId = rest.optLong(Consts.DB_COLUMNS.ID);
			String name = rest.optString(Consts.DB_COLUMNS.NAME);
			String address = rest.optString(Consts.DB_COLUMNS.ADDRESS);
			String phone = rest.optString(Consts.DB_COLUMNS.PHONE);
			if (rest.optString(Consts.DB_COLUMNS.SECONDARY_PHONE) != null) phone2 = rest.optString(Consts.DB_COLUMNS.SECONDARY_PHONE);
			if (rest.optString(Consts.DB_COLUMNS.IMAGE_URL) != null)
			{
				imageUrl = rest.optString(Consts.DB_COLUMNS.IMAGE_URL);
			}
			if (TextUtils.isEmpty(imageUrl) || !imageUrl.equals("null"))
			{
				photos.loadPhoto(imageUrl, restImage);
			}
			GeoPoint gPoint = new GeoPoint(Double.parseDouble(rest.optString(Consts.DB_COLUMNS.LATITUDE)), Double.parseDouble(rest
					.optString(Consts.DB_COLUMNS.LONGITUDE)));
			mMapView = new RestMap(this, gPoint, address);

			restName.setText(name);
			restAddress.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + ((TextView) v).getText()));
					try
					{
						startActivity(intent);
					}
					catch (ActivityNotFoundException ex)
					{
						Toast.makeText(getBaseContext(), "Google Maps is not installed", Toast.LENGTH_LONG).show();
					}
				}
			});
			restAddress.setText(address);
			restPhone.setText(phone);
			Linkify.addLinks(restPhone, Linkify.PHONE_NUMBERS);
			Linkify.addLinks(restPhone2, Linkify.PHONE_NUMBERS);
			if (!TextUtils.isEmpty(phone2))
			{
				restPhone2.setText(phone2);
			}
			else
			{
				restPhone2.setVisibility(View.GONE);
			}
		}
		if (propArr != null)
		{
			for (int i = 0; i < propArr.length(); i++)
			{
				switch (Integer.parseInt(propArr.optJSONObject(i).optString("PROPERTY_ID")))
				{

					case Consts.PROPERTIES.DELIVERY:
						((CheckBox) view.findViewById(R.id.delivery_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.KOSHER:
						((CheckBox) view.findViewById(R.id.kosher_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.KOSHER_MEHADRIN:
						((CheckBox) view.findViewById(R.id.kosher_mehadrin_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.DIS_ACCESS:
						((CheckBox) view.findViewById(R.id.dis_acc_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.CHILD_FRIEND:
						((CheckBox) view.findViewById(R.id.child_friendly_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.EVENT_OK:
						((CheckBox) view.findViewById(R.id.event_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.ROMANTIC:
						((CheckBox) view.findViewById(R.id.romantic_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.CONCERTS:
						((CheckBox) view.findViewById(R.id.concerts_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.OUT_SIDE:
						((CheckBox) view.findViewById(R.id.out_side_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.PARKING:
						((CheckBox) view.findViewById(R.id.parking_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.SMOKING:
						((CheckBox) view.findViewById(R.id.smoking_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.CATERING:
						((CheckBox) view.findViewById(R.id.catering_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.WIRELESS:
						((CheckBox) view.findViewById(R.id.wireless_checkbox)).setChecked(true);
						break;

				}
			}
		}
		return view;

	}

}
